#include "editpost.h"
#include "postmanager.h"
#include <QMouseEvent>

PostManager::PostManager(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_postManager_hideSearch->setIcon(pix);
    ui->btn_postManager_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_postManager_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_postManager_refresh->setIcon(freshPix.scaled(25,25));
    ui->tableWidget_postManager->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_postManager->setSelectionBehavior(QAbstractItemView::SelectRows);

    init();

    //隐藏搜索
    connect(ui->btn_postManager_hideSearch,&QPushButton::clicked,this,[=](){
        ui->widget_57->setHidden(!ui->widget_57->isHidden());
    });
    //    //下一页
    connect(ui->btn_postManager_next,&QPushButton::clicked,this,[=](){
        ui->btn_postManager_next->setEnabled(0);
        currentPage ++;
        getList();
        initTable();
        initPageInfo();
    });
    //上一页
    connect(ui->btn_postManager_pervious,&QPushButton::clicked,this,[=](){
        ui->btn_postManager_pervious->setEnabled(0);
        currentPage --;
        getList();
        initTable();
        initPageInfo();
    });
    //跳转页
    connect(ui->lineEdit_postManager_gotoPage,&QLineEdit::returnPressed,this,[=](){
        int page = ui->lineEdit_postManager_gotoPage->text().toInt();
        ui->lineEdit_postManager_gotoPage->clear();
        if(page < 1 || page > totalPage){
            ui->lineEdit_postManager_gotoPage->setStyleSheet("border:1px solid red;");
            return;
        }
        ui->lineEdit_postManager_gotoPage->setStyleSheet("");
        currentPage = page;
        getList();
        initTable();
        initPageInfo();
    });
    //    每页大小
    connect(ui->comboBox_postManager_pageItem,SIGNAL(currentIndexChanged(int)),this,SLOT(pageSizeChanged(int)));
    //    重置
    connect(ui->btn_postManager_reset,&QPushButton::clicked,this,[=](){
        ui->btn_postManager_reset->setEnabled(0);
        init();
        ui->btn_postManager_reset->setEnabled(1);
    });
    //搜索
    connect(ui->btn_postManager_search,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    //刷新
    connect(ui->btn_postManager_refresh,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    connect(ui->btn_postManager_add,&QPushButton::clicked,this,[=](){
        EditPost *e = new EditPost(-1,sys_normal_disable);
        e->setAttribute(Qt::WA_DeleteOnClose);
        connect(e,&EditPost::success,this,[=](){
            getList();
            initTable();
            initPageInfo();
        });
        e->exec();
    });
    //修改
    connect(ui->btn_postManager_update,&QPushButton::clicked,this,[=](){
        int index = ui->tableWidget_postManager->currentRow();
        if(index < 0) return;
        QString id = ui->tableWidget_postManager->item(index,0)->text();
        EditPost *e = new EditPost(id.toInt(),sys_normal_disable);
        e->setAttribute(Qt::WA_DeleteOnClose);
        connect(e,&EditPost::success,this,[=](){
            getList();
            initTable();
            initPageInfo();
        });
        e->exec();
    });
    //批量删除
    connect(ui->btn_postManager_del,SIGNAL(clicked()),this,SLOT(deleteByIds()));
    //导出
    connect(ui->btn_postManager_export,&QPushButton::clicked,this,[=](){
        utils.exportExcel(ui->tableWidget_postManager,"字典管理表格");
    });
}


void PostManager::pageSizeChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTable();
    initPageInfo();
}

void PostManager::deleteByIds()
{
    QList<QTableWidgetItem*> items = ui->tableWidget_postManager->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 5;    //选中的行数
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget_postManager->row(items.at(i * 5));
        if(i != rowCount - 1){
            ids += ui->tableWidget_postManager->item(index,0)->text() + ",";
        }else{
            ids += ui->tableWidget_postManager->item(index,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选项吗?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QByteArray *bytes = api.deleteItems(ids);
    QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
    if(200 == obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        getList();
        initTable();
        initPageInfo();
    }
}

void PostManager::init()
{
    getDictList();
    initSearchArea();
    getList();
    initTable();
    initPageInfo();
}

void PostManager::getDictList()
{
    sys_normal_disable.clear();
    QByteArray *data = utils.getDictType("sys_normal_disable");
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("data").toArray();
    for(int i = 0;i< arr.size();i++){
        sys_normal_disable.append(DictData::toDictData(arr.at(i).toObject()));
    }
}

void PostManager::initSearchArea()
{
    ui->lineEdit_postManager_postName->clear();
    ui->lineEdit_postManager_postCode->clear();
    ui->comboBox_postManager_status->clear();
    ui->comboBox_postManager_status->addItem("");
    for(int i = 0;i< sys_normal_disable.size();i++){
        ui->comboBox_postManager_status->addItem(sys_normal_disable.at(i).dictLabel,sys_normal_disable.at(i).dictValue);
    }
}

void PostManager::getList()
{
    postList.clear();
    QString code = ui->lineEdit_postManager_postCode->text();
    QString status = ui->comboBox_postManager_status->itemData(
                                                              ui->comboBox_postManager_status->currentIndex()).value<QString>();
    QString postName = ui->lineEdit_postManager_postName->text();

    QByteArray *data = api.getList(currentPage,pageSize,code,postName,status);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("rows").toArray();
    total = obj.value("total").toInt();
    for(int i = 0;i< arr.size();i++){
        postList.append(Post::toPost(arr.at(i).toObject()));
    }
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_postManager_count->setText("共"+QString::number(total)+"条");
}

void PostManager::initTable()
{
    ui->tableWidget_postManager->setSortingEnabled(0);
    ui->tableWidget_postManager->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget_postManager->clear();
    QStringList columnHeader;
    columnHeader << "岗位编号" << "岗位编码" << "岗位名称" << "岗位排序" << "状态" << "创建时间" << "操作";
    ui->tableWidget_postManager->setColumnCount(columnHeader.size());
    ui->tableWidget_postManager->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget_postManager->setRowCount(postList.size());
    for(int i = 0;i< postList.size();i++){
        ui->tableWidget_postManager->setColumnWidth(i,150);
        ui->tableWidget_postManager->setRowHeight(i,38);
        QString postId = QString::number(postList.at(i).postId);
        ui->tableWidget_postManager->setItem(i,0,new QTableWidgetItem(postId));
        ui->tableWidget_postManager->setItem(i,1,new QTableWidgetItem(postList.at(i).postCode));
        ui->tableWidget_postManager->setItem(i,2,new QTableWidgetItem(postList.at(i).postName));
        ui->tableWidget_postManager->setItem(i,3,new QTableWidgetItem(QString::number(postList.at(i).postSort)));
        QLabel *label = new QLabel();
        for (int j = 0; j < sys_normal_disable.size(); ++j) {
            if(postList.at(i).status == sys_normal_disable.at(j).dictValue){
                label->setText(sys_normal_disable.at(j).dictLabel);
                label->setStyleSheet(utils.backShowStyle[sys_normal_disable.at(j).listClass]);
                break;
            }
        }
        label->setFixedSize(46,20);
        label->setAlignment(Qt::AlignCenter);
        QWidget *widget = new QWidget();
        QHBoxLayout* hLayout = new QHBoxLayout(widget);
        label->setAlignment(Qt::AlignCenter);
        hLayout->addWidget(label);
        ui->tableWidget_postManager->setCellWidget(i,4,widget);
        ui->tableWidget_postManager->setItem(i,5,new QTableWidgetItem(postList.at(i).createTime));
        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnUpdate = new QPushButton;
        QPushButton *btnDelete = new QPushButton;
        connect(btnDelete,&QPushButton::clicked,this,[=](){
            int flag  = QMessageBox::question(0,"提示","确定删除该项吗?",QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                if(flag == QMessageBox::No) return;
                QByteArray *bytes = api.deleteItems(postId);
                QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
                if(200 == obj.value("code").toInt()){
                    QMessageBox::warning(0,"提示",obj.value("msg").toString());
                    getList();
                    initTable();
                    initPageInfo();
                }
            }
        });
        connect(btnUpdate,&QPushButton::clicked,this,[=](){;
            EditPost *e = new EditPost(postId.toInt(),sys_normal_disable);
            e->setAttribute(Qt::WA_DeleteOnClose);
            connect(e,&EditPost::success,this,[=](){
                getList();
                initTable();
                initPageInfo();
            });
            e->exec();
        });
        btnDelete->setText("🗑删除");
        btnDelete->setFixedSize(80,35);
        btnUpdate->setText("🖍修改");
        btnUpdate->setFixedSize(80,35);
        btnUpdate->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(231, 250, 240);color: black;}QPushButton:hover {background-color: rgb(19, 206, 102);}QPushButton:pressed {background-color: rgb(19, 150, 102);}");
        btnDelete->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");
        tmp_layout->addWidget(btnUpdate);
        tmp_layout->addWidget(btnDelete);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        ui->tableWidget_postManager->setCellWidget(i,6,tmp_widget);
    }
    // 设置单元格内容居中对齐
    ui->tableWidget_postManager->setColumnWidth(6,167);
    for (int row = 0; row < ui->tableWidget_postManager->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_postManager->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_postManager->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget_postManager->setSortingEnabled(1);
}

void PostManager::initPageInfo()
{
    if(currentPage == 1){
        ui->btn_postManager_pervious->setEnabled(0);
    }else{
        ui->btn_postManager_pervious->setEnabled(1);
    }
    ui->label_postManager_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_postManager_next->setEnabled(0);
    }else{
        ui->btn_postManager_next->setEnabled(1);
    }
}
